import axios from 'axios';
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { message } from 'ant-design-vue';
import { getToken, clearToken } from '@/utils/auth';

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

export interface HttpResponse<T = unknown> {
  status: number;
  errorMessage: string;
  code: number;
  data: T;
}

axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      config.headers.Gogptauthorization = token;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 401) {
        clearToken()
        message.error('登录失效，请重新登录')
      } else {
        message.error(res.message)
      }
      return Promise.reject(new Error(res.errorMessage || 'Error'));
    }
    return res;
  },
  (error) => {
    console.log(error);

    if (error.response.status === 401) {
      clearToken()
      message.error('登录失效，请重新登录')
    } else {
      message.error({
        content: error.message || 'Request Error',
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
